package com.purplesoft.zettl.Activities;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.text.InputFilter;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;
import android.widget.Toast;

import com.purplesoft.zettl.R;
import com.purplesoft.zettl.Database.DatabaseExecuter;
import com.purplesoft.zettl.DatabaseTables.TblItems;
import com.purplesoft.zettl.DatabaseTables.TblMeasures;
import com.purplesoft.zettl.Utilities.DecimalDigitsInputFilter;

public class EditMeasures extends Activity implements OnClickListener, android.content.DialogInterface.OnClickListener {

	private ListView lvMeasures;
	private ImageButton btAddNewMeasure;
	private TextView tvMeasure, tvAddNewMeasure, etMeasureMin, etMeasureMax, etMeasureIncreaseBy, etMeasurePricePer;
	private EditText etMeasure, etMeasureShort;
	private Button btCancel;
	private Cursor csTblMeasures;
	private SimpleCursorAdapter laMeasures;
	private Dialog editMeasureDialog;
	private AlertDialog alertDialogMeasure;
	private DatabaseExecuter dbExec;
	private String measure;
	private final int OK_BUTTON = 1, YES_NO_BUTTON = 2;
	private final int MEASURE_ID_DEFAULT_VALUE = -99;
	private final String EQUAL_OPERATION = " = ", NOT_EQUAL_OPERATION = " != ";
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setTheme(R.style.Theme_Purple);
		setContentView(R.layout.edit_measure);
        
		lvMeasures = (ListView) findViewById(R.id.lvMeasure_EditMeasure);
		btAddNewMeasure = (ImageButton) findViewById(R.id.btAddMeasure_EditMeasure);
		tvAddNewMeasure = (TextView) findViewById(R.id.tvAddNewMeasure_EditMeasure);
		btCancel = (Button) findViewById(R.id.btCancel_EditMeasure);
		
		dbExec = new DatabaseExecuter(this);
		
		selectDataForLvLists();
		btAddNewMeasure.setOnClickListener(this);
		tvAddNewMeasure.setOnClickListener(this);
		btCancel.setOnClickListener(this);
	}

	private void selectDataForLvLists() {
		csTblMeasures = dbExec.queryFromTblMeasures(TblMeasures.Columns._ID, MEASURE_ID_DEFAULT_VALUE, NOT_EQUAL_OPERATION);
		startManagingCursor(csTblMeasures);
		laMeasures = new SimpleCursorAdapter(this, R.layout.edit_measure_row, csTblMeasures, new String[] { TblMeasures.Columns.Measure }, new int[] { R.id.tvMeasure_EditMeasureRow });
		lvMeasures.setAdapter(laMeasures);
	}

	public void onClick(View view) {
		switch(view.getId()) {
		case R.id.btAddMeasure_EditMeasure:
			showEditMeasureDialog(null);
			break;
		case R.id.tvAddNewMeasure_EditMeasure:
			showEditMeasureDialog(null);
			break;
		case R.id.btCancel_EditMeasure:
			finish();
			break;
		case R.id.btSave_EditMeasureDialog:
			saveMeasure();
			break;
		case R.id.btCancel_EditMeasureDialog:
			measure = null;
			editMeasureDialog.dismiss();
			break;
		}
	}
	
	public void selectMeasure(View view) {
		RelativeLayout editMeasureRow = (RelativeLayout) view.getParent();
		tvMeasure = (TextView) editMeasureRow.findViewById(R.id.tvMeasure_EditMeasureRow);
		measure = tvMeasure.getText().toString();
		csTblMeasures = dbExec.queryFromTblMeasures(TblMeasures.Columns.Measure, measure, EQUAL_OPERATION);
		startManagingCursor(csTblMeasures);
		Bundle resultBundle = new Bundle();
		resultBundle.putString(TblMeasures.Columns.Measure, measure);
		resultBundle.putInt(TblMeasures.Columns._ID, csTblMeasures.getInt(csTblMeasures.getColumnIndex(TblMeasures.Columns._ID)));
		Intent resultIntent = new Intent().putExtras(resultBundle);
		setResult(RESULT_OK, resultIntent);
		finish();
	}
	
	public void editMeasure(View view) {
		RelativeLayout editMeasureRow = (RelativeLayout) view.getParent();
		tvMeasure = (TextView) editMeasureRow.findViewById(R.id.tvMeasure_EditMeasureRow);
		measure = tvMeasure.getText().toString();
		showEditMeasureDialog(measure);
	}

	public void deleteMeasure(View view) {
		RelativeLayout editMeasureRow = (RelativeLayout) view.getParent();
		tvMeasure = (TextView) editMeasureRow.findViewById(R.id.tvMeasure_EditMeasureRow);
		measure = tvMeasure.getText().toString();
		showAlertDialog(getResources().getString(R.string.delete_measure), YES_NO_BUTTON);
	}
	
	private boolean checkIfAllFieldsAreFilled() {
		if (etMeasure.getText().toString().equals("")) {
			showAlertDialog(getResources().getString(R.string.fill_in_measure), OK_BUTTON);
			return false;
		} else if (etMeasureShort.getText().toString().equals("") || etMeasureMin.getText().toString().equals("") || etMeasureMin.getText().toString().equals("") || etMeasureIncreaseBy.getText().toString().equals("") || etMeasurePricePer.getText().toString().equals("")) {
			showAlertDialog(getResources().getString(R.string.fill_in_all_fields), OK_BUTTON);
			return false;
		} else {
			return true;
		}
	}

	private void saveMeasure() {
		if (checkIfAllFieldsAreFilled() == false) return;
		if (measure !=null) {
			if (dbExec.updateTblMeasures(measure, etMeasure.getText().toString(), etMeasureShort.getText().toString(), etMeasureMin.getText().toString(), etMeasureMax.getText().toString(), etMeasureIncreaseBy.getText().toString(), etMeasurePricePer.getText().toString()) == false) {
				showAlertDialog(getResources().getString(R.string.measure_already_exists), OK_BUTTON);
				etMeasure.selectAll();
				return;
			}
		} else {
			if (dbExec.insertIntoTblMeasures(etMeasure.getText().toString(), etMeasureShort.getText().toString(), etMeasureMin.getText().toString(), etMeasureMax.getText().toString(), etMeasureIncreaseBy.getText().toString(), etMeasurePricePer.getText().toString()) == false) {
				showAlertDialog(getResources().getString(R.string.measure_already_exists), OK_BUTTON);
				etMeasure.selectAll();
				return;
			}
		}
			measure = null;
			selectDataForLvLists();
			editMeasureDialog.dismiss();
	}

	private void showAlertDialog(String alertText, int buttons) {
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		switch(buttons) {
		case OK_BUTTON:
			builder.setMessage(alertText);
			builder.setNeutralButton(R.string.ok, this);
			break;
		case YES_NO_BUTTON:
			builder.setMessage(String.format(alertText, measure));
			builder.setCancelable(false);
		    builder.setPositiveButton(R.string.yes, this);
		    builder.setNegativeButton(R.string.no, this);
		    break;
		}
		if (alertDialogMeasure == null || !alertDialogMeasure.isShowing()) {
			alertDialogMeasure = builder.create();
			alertDialogMeasure.show();
		}
	}

	private void showEditMeasureDialog(String measure) {
		RelativeLayout viewGroup = (RelativeLayout) findViewById(R.id.EditMeasureDialog);
		LayoutInflater layoutInfater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		View layout = layoutInfater.inflate(R.layout.edit_measure_dialog, viewGroup);
		
		if (editMeasureDialog == null || !editMeasureDialog.isShowing()) {
			editMeasureDialog = new Dialog(this, android.R.style.Theme_Translucent_NoTitleBar);
			editMeasureDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
			editMeasureDialog.setContentView(layout);
			
			WindowManager.LayoutParams lp = editMeasureDialog.getWindow().getAttributes();
			lp.dimAmount=0.6f;
			editMeasureDialog.getWindow().setAttributes(lp);  
			editMeasureDialog.getWindow().addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
			editMeasureDialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
			
			Button btSaveEditMeasureDialog = (Button) editMeasureDialog.findViewById(R.id.btSave_EditMeasureDialog);
			Button btCancelEditMeasureDialog = (Button) editMeasureDialog.findViewById(R.id.btCancel_EditMeasureDialog);
			TextView tvTitleEditMeasureDialog = (TextView) editMeasureDialog.findViewById(R.id.tvTitle_EditMeasureDialog);
			etMeasure = (EditText) editMeasureDialog.findViewById(R.id.etMeasure_EditMeasureDialog);
			etMeasureShort = (EditText) editMeasureDialog.findViewById(R.id.etMeasureShort_EditMeasureDialog);
			etMeasureMin = (EditText) editMeasureDialog.findViewById(R.id.etMeasureMin_EditMeasureDialog);
			etMeasureMax = (EditText) editMeasureDialog.findViewById(R.id.etMeasureMax_EditMeasureDialog);
			etMeasureIncreaseBy = (EditText) editMeasureDialog.findViewById(R.id.etMeasureIncreaseBy_EditMeasureDialog);
			etMeasurePricePer = (EditText) editMeasureDialog.findViewById(R.id.etMeasurePricePer_EditMeasureDialog);
			
			if (measure != null) {
				tvTitleEditMeasureDialog.setText(getResources().getString(R.string.edit_measure));
				btSaveEditMeasureDialog.setText(R.string.alter);
				csTblMeasures = dbExec.queryFromTblMeasures(TblMeasures.Columns.Measure, measure, EQUAL_OPERATION);
				startManagingCursor(csTblMeasures);
				etMeasure.setText(measure);
				etMeasureShort.setText(csTblMeasures.getString(csTblMeasures.getColumnIndex(TblMeasures.Columns.MeasureShort)));
				etMeasureMin.setText(csTblMeasures.getString(csTblMeasures.getColumnIndex(TblMeasures.Columns.Min)));
				etMeasureMax.setText(csTblMeasures.getString(csTblMeasures.getColumnIndex(TblMeasures.Columns.Max)));
				etMeasureIncreaseBy.setText(csTblMeasures.getString(csTblMeasures.getColumnIndex(TblMeasures.Columns.IncreaseBy)));
				etMeasurePricePer.setText(csTblMeasures.getString(csTblMeasures.getColumnIndex(TblMeasures.Columns.PricePer)));
				etMeasure.selectAll();
				etMeasureShort.setSelectAllOnFocus(true);
				etMeasureMin.setSelectAllOnFocus(true);
				etMeasureMax.setSelectAllOnFocus(true);
				etMeasureIncreaseBy.setSelectAllOnFocus(true);
				etMeasurePricePer.setSelectAllOnFocus(true);
				etMeasureMin.setFilters(new InputFilter[] {new DecimalDigitsInputFilter(5,3)});
				etMeasureMax.setFilters(new InputFilter[] {new DecimalDigitsInputFilter(5,3)});
				etMeasureIncreaseBy.setFilters(new InputFilter[] {new DecimalDigitsInputFilter(5,3)});
				etMeasurePricePer.setFilters(new InputFilter[] {new DecimalDigitsInputFilter(5,3)});
			}
			
			btSaveEditMeasureDialog.setOnClickListener(this);
			btCancelEditMeasureDialog.setOnClickListener(this);
			
			editMeasureDialog.show();
		}
	}

	public void onClick(DialogInterface dialog, int which) {
		switch(which) {
		case -1: // Yes
				csTblMeasures = dbExec.queryFromTblMeasures(TblMeasures.Columns.Measure, measure, EQUAL_OPERATION);
				startManagingCursor(csTblMeasures);
				dbExec.updateTblItems(TblItems.Columns.MeasureID, csTblMeasures.getInt(csTblMeasures.getColumnIndex(TblMeasures.Columns._ID)), MEASURE_ID_DEFAULT_VALUE);
				dbExec.deleteFromTblMeasures(measure);
				selectDataForLvLists();
				Toast.makeText(this, String.format(getResources().getString(R.string.measure_deleted), measure), Toast.LENGTH_LONG).show();
				measure = null;
		}
	}
}
